/*
 * 文件名：CotBackupController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月16日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.bpa.domain.BpaProjectDomain;
import top.infopub.mgr.bpa.domain.CotBackupDomain;
import top.infopub.mgr.bpa.jsonVo.ContractReviewJsonVo;
import top.infopub.mgr.bpa.jsonVo.CotBackupJsonVo;
import top.infopub.mgr.bpa.service.*;
import top.infopub.mgr.bpa.vo.CotBackupVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.ContractExtSup;
import top.infopub.model.bpa.CotBackup;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**商务事项
 * @author wuzhiyang
 * @version 2020年3月16日
 * @see CotBackupController
 * @since商务管理/商务事项/总包备案合同
 */
@Controller
@RequestMapping("/cotBackup")
public class CotBackupController extends GenericFlowController {


    @Autowired
    private CotBackupService cotBackupService;
    @Autowired
    private ContractNegService contractNegService;

    @Autowired
    private ProProcessManageService proProcessManageService;
    @Autowired
    private BpaProcessManageService bpaProcessManageService;


    /**
     * 总包备案合同列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<CotBackupDomain> queryDataByCondition(CotBackupVo cotBackupVo, ParamPage paramPage) throws ParseException {
        Page<CotBackupDomain> page = new Page<CotBackupDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = cotBackupService.selectPageByDomainWhere(page, cotBackupVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "cotBackup";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传商务事项-总包备案事项附件-文件名:"
                                                                      + filePath + "，文件路径:"
                                                                      + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     * @param id 总包备案合同id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        CotBackup cotBackup = cotBackupService.selectBySguid(id);
        request.setAttribute("isAuditFlag", "1");
        if (cotBackup!=null){
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), cotBackup.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(cotBackup.getProcessId()) && cotBackup.getProcessId().length() > 10){
                request.setAttribute("processId", cotBackup.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(cotBackup.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), cotBackup.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return new ModelAndView("bpa/lay-ContractRecord-detail");
    }
    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //审批
        bpaProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /**
    *@Description: 项目下拉
    *@Param:
    *@return:
    *@Author: Tszzzzzzz
    *@date: 2021/6/16
    */
    @RequestMapping("/queryDrop")
    @ResponseBody
    public RspVo queryDrop(){
        //查找通过合同谈判的合同
        List<BpaProjectDomain> bpaProjectDomain = contractNegService.queryByProCode();
        return RspVo.getSuccessResponse(bpaProjectDomain);
    }

    /**
    *@Description: 总包合同详情
    *@Param:
    *@return:
    *@Author: Tszzzzzzz
    *@date: 2021/6/16
    */
    @RequestMapping("/queryBackUpDetail")
    @ResponseBody
    public RspVo queryBackUpDetail(String id){
        //查询总包数据
       CotBackup cotBackup = cotBackupService.queryById(id);
        return RspVo.getSuccessResponse(cotBackup);
    }

    /**
    *@Description: 总包合同新增
    *@Param:
    *@return:
    *@Author: Tszzzzzzz
    *@date: 2021/6/16
    */
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String bodyStr,Integer submitType){
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        CotBackupJsonVo vo = JSON.parseObject(s,CotBackupJsonVo.class);
        CotBackup cotBackup = new CotBackup();
        if (StringUtils.isNotBlank(vo.getCotBackup().getId())){
            //编辑
            BeanUtils.copyProperties(vo.getCotBackup(),cotBackup);
            cotBackup.setUptBy(userDtl.getId());
            cotBackup.setUptTime(new Date());
        }else{ //新增
            BeanUtils.copyProperties(vo.getCotBackup(),cotBackup);
            cotBackup.setAddBy(userDtl.getId());
            cotBackup.setAddTime(new Date());
            cotBackup.setId(IdFactory.getUUIDUpper());
        }
        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(vo.getFileAtt()!=null){
            String[] fileAtt = vo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(userDtl,cotBackup.getProCode(),file);
                attachmentList.add(attachment);
            }
        }
        return cotBackupService.saveAll(cotBackup,attachmentList,bodyStr,userDtl,submitType);
    }
}
